package com.koron.css2.newProjectCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.newProjectCenter.bean.PjCheckInfoBean;
import com.koron.css2.newProjectCenter.bean.query.PjCheckInfoQueryBean;
import com.koron.css2.newProjectCenter.mapper.PjCheckInfoMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.css2.systemManage.bean.OrgUserBean;
import com.koron.css2.systemManage.mapper.OrgUserMapper;
import com.koron.util.Constant;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PjCheckInfoHistory implements ServerInterface {
    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            PjCheckInfoQueryBean pjCheckInfoQueryBean = JsonUtils.objectToPojo(req.getData(), PjCheckInfoQueryBean.class);
            PjCheckInfoMapper pjCheckInfoMapper = factory.getMapper(PjCheckInfoMapper.class);
            OrgUserMapper orgUserMapper = factory.getMapper(OrgUserMapper.class);
            // 1. 查询所有版本的工程验收信息
            Map<String, List<PjCheckInfoBean>> data = new HashMap<String, List<PjCheckInfoBean>>();
            List<PjCheckInfoBean> pjCheckInfoBeanList = pjCheckInfoMapper.getList(pjCheckInfoQueryBean);
            List<PjCheckInfoBean> list = null;
            for (PjCheckInfoBean pjCheckInfo : pjCheckInfoBeanList){
                OrgUserBean orgUser = orgUserMapper.selectByAccount(pjCheckInfo.getCheckStaff());
                pjCheckInfo.setCheckStaffName(orgUser.getUserName());
                if (data.get(String.valueOf(pjCheckInfo.getVersion())) == null){
                    list = new ArrayList<PjCheckInfoBean>();
                    data.put(String.valueOf(pjCheckInfo.getVersion()), list);
                }
                list.add(pjCheckInfo);
            }

            // 2. 根据版本号来聚合数据
           // Map<String, List<PjCheckInfoBean>> versionGroup = pjCheckInfoBeanList.stream().collect(Collectors.groupingBy(PjCheckInfoBean::getVersion));
            // 3. 返回数据
            MessageBean<Map> messageBean = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "工程验收历史数据查看成功", Map.class);
            messageBean.setData(data);
            return messageBean;
        } catch (Exception e) {
            logger.error("工程验收历史数据查看失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "工程验收历史数据查看失败", null);
        }
    }
}
